import createHistory from 'history/createBrowserHistory';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
import * as moment from 'moment';
import 'moment/locale/zh-cn';
import { MainLayout } from './routes/layout';
import { createStore, authRely, registerDefaultApiErrorHandler } from './common';

// 实例化 store
const history = createHistory();
const store = createStore(history, window.___INITIAL_STATE__);

// React Render
const MOUNT_NODE = document.getElementById('root');

let render = () => {
    ReactDOM.render(
        <Provider store={store}>
            <ConnectedRouter history={history}>
                <Router basename={__VIRTUALPATH__}>
                    <MainLayout/>
                </Router>
            </ConnectedRouter>
        </Provider>,
        MOUNT_NODE
    );
};

// 开发工具设置开启
if (__DEV__ && window.devToolsExtension) {
    // window.devToolsExtension.open();
}

// 设置开发环境错误提示
if (__DEV__) {
    if (module.hot) {
        // Development render functions
        const renderApp = render;
        const renderError = (error: any) => {
            const RedBox = require('redbox-react').default;
            ReactDOM.render(<RedBox error={error} />, MOUNT_NODE);
        };

        // Wrap render in try/catch
        render = () => {
            try {
                renderApp();
            } catch (error) {
                renderError(error);
            }
        };
    }
}

moment.locale('zh-cn');
registerDefaultApiErrorHandler();
// 初始化 electron 中的身份信息
if (window.__ELE__) {
    authRely.saveUser(
        JSON.stringify(
            window.getUserCache()
        )
    );

    const autoComputeRequestToken = () => {
        window.computeRequestToken();
        setTimeout(() => {
            autoComputeRequestToken();
        }, 60000);
    };

    autoComputeRequestToken();
}

render();
